package com.webserver.core;

import com.webserver.controller.UserController;
import com.webserver.http.HttpContext;
import com.webserver.http.HttpServletRequest;
import com.webserver.http.HttpServletResponse;

import java.io.File;
import java.net.URISyntaxException;

/**
 * 处理请求的环节
 */
public class DispatchServlet {

     //表示sources下的static目录，实际是运行时编译后target/classes下的static目录
     private static File staticDir;
     static{
          try {
               staticDir=new File(
                       ClientHandler.class.getClassLoader().getResource(
                               "./static"
                       ).toURI()
               );
          } catch (URISyntaxException e) {
               e.printStackTrace();
          }
     }
     public void service(HttpServletRequest request, HttpServletResponse response){
          //根据用户的请求获取用户所登录的网址（抽象路径）
          String path = request.getRequestURI();
          System.out.println(path);
          //判断该请求是否为为请求某个业务
          if("/myweb/reg".equals(path)){
               UserController controller = new UserController();
               controller.register(request,response);
          }
          else {
               //去static目录下根据用户请求的抽象路径定位下面的文件
               File file = new File(staticDir, path);
               if (file.isFile()) {//判断确实是个文件
                    response.setContentFile(file);
               } else {//文件不存在或为目录
                    response.setStatusCode(404);
                    response.setStatusReason("Not Found");
                    file = new File(staticDir, "/root/404.html");
                    response.setContentFile(file);
               }
          }
     }
}
